package com.cp.www.ws.listener;

import org.kurento.client.EventListener;
import org.kurento.client.IceCandidateFoundEvent;
import org.kurento.jsonrpc.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.google.gson.JsonObject;

public final class CandidateFoundListener implements EventListener<IceCandidateFoundEvent> {

	private WebSocketSession session;

	private Logger log = LoggerFactory.getLogger(CandidateFoundListener.class);

	public CandidateFoundListener(WebSocketSession session) {
		this.session = session;
	}

	@Override
	public void onEvent(IceCandidateFoundEvent event) {
		if (session == null) {
			return;
		}
		JsonObject response = new JsonObject();
		response.addProperty("id", "iceCandidate");
		response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
		try {
			synchronized (session) {
				session.sendMessage(new TextMessage(response.toString()));
			}
		} catch (Exception e) {
			log.error("Exception sending message", e.getMessage());
		}

	}

}
